import { createDirAndWriteFile } from "@ap/util/fs";
import { tempPath } from "@ap/util/tempPath";
import {
  openResourcesMsg,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { openFileDocument } from "@ap/util/vscode/openAndWriteTextDocument";
import path from "path";

function formatTime() {
  return new Intl.DateTimeFormat("zh-CN", {
    dateStyle: "full",
    timeStyle: "long",
  }).format(new Date());
}

function processResources(
  resources: Record<string, any> | null,
  config: Record<string, any>,
  dtsString: string,
  resourceType: string,
  resourceTypeEn: string,
  mapId: string,
): string {
  let result = `${dtsString}

/**
 * @description [ID:${mapId}]地图${resourceType}资源
 * @date ${formatTime()}
 */
type Game${resourceTypeEn}Assets = `;

  if (resources && Object.keys(resources).length > 0) {
    for (const key of Object.keys(resources)) {
      config[key] = {
        prefix: `#${key}`,
        body: [`'${key}'`],
        description: `地图${resourceType}资源 [ID:${mapId}]`,
        scope: "typescript,javascript",
      };
      result += `'${key.replace(/'/g, "\\'")}' | `;
    }
    result = result.substring(0, result.length - 2) + ";";
  } else {
    result += "never;";
  }

  return result;
}

export async function transformDao3Resources(
  prop: {
    audioAsset: Record<string, any> | null;
    pictureAssets: Record<string, any> | null;
    modelAssets: Record<string, any> | null;
  },
  mapId: string,
) {
  const config: Record<string, any> = {};
  const pathG = tempPath;

  if (!pathG) {
    return;
  }

  const snippetsFilePath = path.join(
    pathG,
    ".vscode",
    "dao3-GameAssets.code-snippets",
  );
  const dtsServerFilePath = path.join(
    pathG,
    "server",
    "types",
    "GameAssets.d.ts",
  );
  const dtsClientFilePath = path.join(
    pathG,
    "client",
    "types",
    "GameAssets.d.ts",
  );
  let configDts =
    "// 快捷键Alt+Y 或 右上角同步地图资源按钮，可以重新同步地图资源";

  configDts = processResources(
    prop.audioAsset,
    config,
    configDts,
    "音频",
    "Audio",
    mapId,
  );
  configDts = processResources(
    prop.pictureAssets,
    config,
    configDts,
    "图片",
    "Picture",
    mapId,
  );
  configDts = processResources(
    prop.modelAssets,
    config,
    configDts,
    "模型",
    "Model",
    mapId,
  );

  createDirAndWriteFile(snippetsFilePath, JSON.stringify(config, null, 2));
  createDirAndWriteFile(dtsServerFilePath, configDts);
  createDirAndWriteFile(dtsClientFilePath, configDts);

  if (await openResourcesMsg()) {
    openFileDocument("/server/types/GameAssets.d.ts");
  }
}
